package edu.wichita.weighin;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;

public class MetalResultsActivity extends Activity {
    
    public static final String PREFS_INFO = "info"; //private file for displaying info
    private static final String PREFS_INFO_SOURCE = "s";
    private static final String PREFS_INFO_MATERIAL = "m";
    private static final String PREFS_INFO_PRICE = "p";
    private static final String PREFS_INFO_WEIGHT = "w";
    
    String metalName;
    float metalWeight;
    float metalPrice;
    float initialPrice, actualPrice;
    String metalSource;
    String goldKarat;
    TextView textMetalName;
    TextView textMetalWeight;
    TextView textMetalPrice;
    TextView textMetalSource;
    
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
    String weightString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_metal_results);
        weightString = Float.toString(metalWeight);
        
        // get the ListView
        expListView = (ExpandableListView) findViewById(R.id.expandableListView_weight);

        // preparing list data
        try {
            prepareListData("Choose a weight");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);
        
        // ListView Group click listener
        expListView.setOnGroupClickListener(new OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                    int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // ListView Group expanded listener
        expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                //Toast.makeText(getApplicationContext(),
                //listDataHeader.get(groupPosition) + " Expanded",
                //Toast.LENGTH_SHORT).show();
            }
        });
        
        // ListView Group collapsed listener
        expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                //Toast.makeText(getApplicationContext(),
                //listDataHeader.get(groupPosition) + " Collapsed",
                //Toast.LENGTH_SHORT).show();
            }
        });

        // ListView on child click listener
        expListView.setOnChildClickListener(new OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
                
                if(parent.isGroupExpanded(groupPosition)) {
                    parent.collapseGroup(groupPosition);
                }
                weightString = listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition);
                ChooseMetalDialogFragment dialog = new ChooseMetalDialogFragment();
                
                dialog.show(getFragmentManager(), "metal");
                return false;
            }
        });
        
        SharedPreferences infoPref = getSharedPreferences(PREFS_INFO, Context.MODE_PRIVATE);
        textMetalName = (TextView) findViewById(R.id.results_metal_chosen);
        textMetalWeight = (TextView) findViewById(R.id.metal_weight);
        textMetalPrice = (TextView) findViewById(R.id.metal_price);
        textMetalSource = (TextView) findViewById(R.id.metal_source);
        
        metalName = infoPref.getString(PREFS_INFO_MATERIAL, "N/A");
        textMetalName.setText(metalName);
        metalWeight = infoPref.getFloat(PREFS_INFO_WEIGHT, 0.00f);
        textMetalWeight.setText(Float.toString(metalWeight));
        textMetalSource.setText(infoPref.getString(PREFS_INFO_SOURCE, "N/A"));
        initialPrice = infoPref.getFloat(PREFS_INFO_PRICE, 0.00f);
        
        if (metalName.equals("COPPER")) {
            actualPrice = (float) ((initialPrice / 453.592) * metalWeight);
        } else {
            actualPrice = (float) ((initialPrice / 31.1034768) * metalWeight);
            if (metalName.equals("GOLD 24K")) {
            	actualPrice *= (float) 0.9995;
            } else if (metalName.equals("GOLD 23K")) {
            	actualPrice *= (float) 0.9583;
            } else if (metalName.equals("GOLD 22K")) {
            	actualPrice *= (float) 0.9166;
            } else if (metalName.equals("GOLD 18K")) {
            	actualPrice *= (float) 0.7500;
            } else if (metalName.equals("GOLD 14K")) {
            	actualPrice *= (float) 0.5833;
            }
        }
        NumberFormat currencyFormatter;
        currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
        textMetalPrice.setText(currencyFormatter.format(actualPrice));
    }
    
    /*public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.metals_menu, menu);
        return true;
    }*/
       
    private void prepareListData(String header) throws IOException {
        
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding child data
        listDataHeader.add(header);
        // Adding child data
        List<String> listOfMetals = new ArrayList<String>();
        FileInputStream fin = openFileInput("storedweights");
        int c;
        String temp = "";
        while((c = fin.read()) != -1) {
            temp = "";
            temp = temp + Character.toString((char)c);
            while ((c = fin.read()) != '\n') {
                temp = temp + Character.toString((char)c);
            }
            listOfMetals.add(temp);
        }
        fin.close();
        listDataChild.put(listDataHeader.get(0), listOfMetals); // Header, Child data
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.metal_results, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    public void onUserSelectValue(String selectedValue) {
        metalName = selectedValue;
        new PriceFetch(getApplicationContext()).pickData(metalName, Float.parseFloat(weightString));
    }
}